import GameUtil from './GameUtil';
import TtUtil from './TtUtil';


export default class WebSocketClass {
    static wsArray = [];
    static getNhwcUrl() {
        return 'ws://192.168.0.198:12346/game1?openId='+ReadLocal('usid','1');
        return 'wss://ws.meappstore.top/game1?openId='+ReadLocal('usid','1');
    }
    static getChatUrl(){
        return 'ws://192.168.0.198:16888/chat?openId='+ReadLocal('usid','1');
    }
    /**
     *
     */
    constructor(url,onMessage,isNeedReconnect,back?) {
        this.connectSocket(url,onMessage,isNeedReconnect,back);
    }
    _socketOpen: boolean = false;             //是否链接成功
    set socketOpen(value : boolean){
        this._socketOpen = value;
        Log('设置socket开关:',value)
    }
    get socketOpen(){
        return this._socketOpen;
    }
    reconnectInterval: any;
    heartBeatTimer = null;               //心跳计时器id

    ws = null;
    registUrl = null;
    registHander = null;
    registBack = null;
    needReconnect = false;
    isReconent = false;


    //链接socket
    connectSocket(url,onMessage,isNeedReconnect,back?) {
        this.registUrl = url;
        this.registBack = back;
        this.registHander = onMessage;
        this.needReconnect = isNeedReconnect;
        Log('连接socket :',url)
        if (cc.sys.platform == cc.sys.WECHAT_GAME){
            this.ttSocket(url,onMessage,back);
        }
        else{
            this.httpSocket(url,onMessage,back);
        }
    }
    ttSocket(url,onMessage,back?){
        let self = this;
        Log('连接地址:',url)
        this.ws = tt.connectSocket({
            url: url,
            success: function (res) {
                // console.log('========wx websocket 链接接口成功:');
            },
            fail: function (res) {
                // console.log('========wx websocket 链接接口失败:', JSON.stringify(res));
            },
        });
        this.ws.onOpen((event) => {
            Log('===========WebSocket onSocketOpen')
            WebSocketClass.wsArray.push(self.ws);
            Log('wxArray长度',WebSocketClass.wsArray.length)

            self.socketOpen = true;
            clearInterval(self.heartBeatTimer);
            //开始心跳
            // self.requestHeartBeat();
            self.heartBeatTimer = self.sendServerFlag();
            back && back(true);

        });

        this.ws.onMessage((event) => {
            // console.log('============收到返回数据：',JSON.stringify(event));
            // Log('===========WebSocket onSocketClose')
            // self.handleOnMessage(event.data);
            onMessage(event.data);
        });

        this.ws.onError((event) => {
            clearInterval(self.heartBeatTimer);
            self.socketOpen = false;
            self.heartBeatTimer = null;
            Log('===========WebSocket onSocketError: ' + JSON.stringify(event))
            TtUtil.showWxText('连接服务器失败', 1, 2000);
            TtUtil.hideLoading();
            setTimeout(()=>{
                back && back(false);
            },1000)
            let index = WebSocketClass.wsArray.indexOf(self.ws);
            if (index >=0 ){
                WebSocketClass.wsArray.splice(index,1);
            }
            Log('wxArray长度',WebSocketClass.wsArray.length)

        });
        this.ws.onClose((event) => {
            Log('===========WebSocket onSocketClose: ' + JSON.stringify(event))
            self.socketOpen = false;
            if(self.needReconnect == false){
                clearInterval(self.heartBeatTimer);
            }
            self.heartBeatTimer = null;
            TtUtil.hideLoading();
            let index = WebSocketClass.wsArray.indexOf(self.ws);
            if (index >=0 ){
                WebSocketClass.wsArray.splice(index,1);
            }
            Log('wxArray长度',WebSocketClass.wsArray.length)
        });
    }
    httpSocket(url,onMessage,back?){
        let self = this;
        Log('连接地址:',url)
        this.ws = new WebSocket(url);//, null, cc.url.raw('resources/raw/215072411660467.pem'));
        this.ws.binaryType = "arraybuffer";
        this.ws.onopen = (event) => {
            Log('===========WebSocket onSocketOpen')
            WebSocketClass.wsArray.push(self.ws);
            Log('wxArray长度',WebSocketClass.wsArray.length)

            self.socketOpen = true;
            clearInterval(self.heartBeatTimer);
            //开始心跳
            // self.requestHeartBeat();
            self.heartBeatTimer = self.sendServerFlag();
            back && back(true);
        };

        this.ws.onmessage = (event) => {
            // console.log('============收到返回数据：',JSON.stringify(event));
            // Log('===========WebSocket onSocketClose')
            // self.handleOnMessage(event);
            onMessage(event.data)
        };

        this.ws.onerror = (event) => {
            let index = WebSocketClass.wsArray.indexOf(self.ws);
            if (index >=0 ){
                WebSocketClass.wsArray.splice(index,1);
            }
            Log('wxArray长度',WebSocketClass.wsArray.length)
            self.socketOpen = false;
            if(self.needReconnect == false){
                clearInterval(self.heartBeatTimer);
                self.heartBeatTimer = null;
            }
            Log('===========WebSocket onSocketError: ' + JSON.stringify(event))
            TtUtil.showWxText('连接服务器失败', 1, 2000);
            setTimeout(()=>{
                back && back(false);
            },1000)

        };
        this.ws.onclose = (event) => {
            let index = WebSocketClass.wsArray.indexOf(self.ws);
            if (index >=0 ){
                WebSocketClass.wsArray.splice(index,1);
            }
            Log('wxArray长度',WebSocketClass.wsArray.length)
            Log('===========WebSocket onSocketClose: ' + JSON.stringify(event))
            self.socketOpen = false;
            if(self.needReconnect == false){
                clearInterval(self.heartBeatTimer);
                self.heartBeatTimer = null;
            }
        };
    }
    closeSocket(){
        if (this.ws){
            this.ws.close();
        }
        if (this.heartBeatTimer){
            clearInterval(this.heartBeatTimer);
        }
    }

    // //处理接受到的数据
    // handleOnMessage(event) {
    //     let self = this;
    //     var msg = event.data;
    //     cc.find('Canvas').emit('Socket', msg);
    // }

    /**
     * 发送长连接消息
     */
    sendSocketMessage(msg) {
        if (this.socketOpen) {
            if (cc.sys.platform == cc.sys.WECHAT_GAME){
                this.ws.send({
                    'data' : msg,
                    success(res){
                        Log('发送成功:',res)
                    },
                    fail(res){
                        Log('发送失败:',res)
                    }
                })
            }
            else{
                this.ws.send(msg);
            }
            Log('发送消息:',msg)
        }
        else if (msg === '0'){
            if (this.needReconnect){
                this.reconnection();
            }
            else{
                TtUtil.hideLoading();
                Log('Url:',this.registUrl)
                // UIHelper.addClearPop('已与服务器断开连接',()=>{
                //     GameUtil.gotoSceneByPage('MainScene');
                // })
            }
        }
        if (!this.socketOpen && !this.isReconent){
            TtUtil.hideLoading();
            Log('Url:',this.registUrl)
            // UIHelper.addClearPop('已与服务器断开连接',()=>{
            //     GameUtil.gotoSceneByPage('MainScene');
            // })
        }
    }
    requestHeartBeat() {
        this.sendSocketMessage('0');
    }
    /**
     * 同服务器测试心跳
     */
    sendServerFlag() {
        if (this.heartBeatTimer) {
            clearInterval(this.heartBeatTimer)
        }
        let id = setInterval(() => {
            this.requestHeartBeat();
        }, 5000)
        return id;
    }


    /**
     * 处理网络断线重连
     */
    reconnection() {
        Log('重新连接')
        // if(this.registUrl == WebSocketClass.getNhwcUrl()){
        //     Log('我次奥?')
        //     TtUtil.showWxText('重新连接中')
        // }
        this.isReconent = true;
        this.connectSocket(this.registUrl,this.registHander,this.needReconnect,(succ)=>{
            if (succ){
                this.socketOpen = true;
                this.isReconent = false;
            }
            // if(this.registUrl == WebSocketClass.getNhwcUrl()){
            //     TtUtil.showWxText('连接成功')
            // }
        });
        return;
    }
}
